<template>
  <div class="c-bg-sgray">
    <div v-if="isCoupons != 1" class="c-w100 c-hh20 c-bg-sgray"></div>
    <div v-if="isCoupons != 1" :class="isApp || $isWxApp() || $unenableTopNav() ? 'c-p-t0' : 'c-p-t68'" class="c-pf c-w100 c-pz100 c-maxw640 c-pb10 c-bg-white">
      <my-small-tabbar :tabList="tabList" :tabIndex="couponType" :tbaIconBg="'c-bg-xmlred'" @changeTab="switchExchange"></my-small-tabbar>
    </div>
    <div :class="isCoupons != 1 ? 'c-mt56' : ''" class="c-pv30 c-ph24">
      <coupon-item-com :couponInfo="item" :successTipType="2" :source="2" v-for="(item,index) in valueVoucherList" :key="index" v-if="valueVoucherList != null && valueVoucherList.length > 0" class="c-mb20">
        <template v-if="isCoupons == 1" v-slot:bodyRight>
          <div class="c-flex-column">
            <div class="c-fc-xblack c-fs26 c-fw-b c-text-ellipsis1">{{item.name}}</div>
            <div class="c-fc-xmlred c-fs24 c-mt16">{{item.usePoints}}{{customPointName}}</div>
          </div>
        </template>
        <template v-if="isCoupons == 1" v-slot:footerRight>
          <div @click="goExchangePoint(item.goodsId)" class="c-fs20 c-ww100 c-hh40 c-br20 c-ml20 c-flex-row c-flex-center xmlred-bd1 c-bg-xmlred c-flex-shrink0 c-fc-white c-fw-b">
            兑换
          </div>
        </template>
      </coupon-item-com>
      <loading-status-tem :dataStatus="dataStatus" :noDataText="couponType == 1 ? '暂无任何兑换券哦' : '暂无任何优惠券哦'"></loading-status-tem>
    </div>
  </div>
  <!-- <div class="c-bg-sgray">
    <div class="c-w100 c-hh20 c-bg-sgray"></div>
    <div v-if="isMall != 1" :class="isApp || $isWxApp() || $unenableTopNav() ? 'c-p-t0' : 'c-p-t68'" class="c-pf c-w100 c-pz100 c-maxw640 c-pb10 c-bg-white">
      <my-small-tabbar :tabList="tabList" :tabIndex="couponType" @changeTab="switchExchange"></my-small-tabbar>
    </div>
    <div class="c-pv30 c-ph24" :class="isMall == 1 ? '':'c-mt56'">
      <div class="c-mb20 c-flex-row c-justify-sb c-aligni-center c-p c-hh160 c-br10 c-text-hidden" v-for="(item,index) in valueVoucherList" v-show="item.leftNum > 0 || (item.prodType ==92 || item.prodType ==200)" :key="index">
        <div class="c-flex-row c-justify-sb c-aligni-center c-bg-white c-fc-gray c-hh160 c-w0 c-flex-grow1 c-ph24 c-pv24">
          <div :class="couponType == 2 ? 'c-justify-sb' : 'c-justify-sa'" class="c-w0 c-flex-grow1 c-flex-column c-h">
            <div class="c-fc-xblack c-fs26 c-fw-b c-text-ellipsis1">{{item.name}}</div>
            <div class="c-fs20" v-if="isCoupons!=1 && item.validStatus != 1 && item.validStatus != 2">
              {{item.startAt.substr(0,10).replace(/-/g, ".")}}-{{item.endAt.substr(0,10).replace(/-/g, ".")}}
            </div>
            <div class="c-fs20" v-else-if="isCoupons!=1">
              {{item.validStatus == 1 ? ('领券当日起' + item.validPeriod + '天内可用') : ('领券次日起' + item.validPeriod + '天内可用')}}
            </div>
            <div class="c-fs28" v-if="couponType == 3 && item.salePrice > 0"><span class="c-fs20">{{'￥' | iosPriceFilter}}</span>{{item.salePrice}}</div>
            <div v-if="couponType >= 2 && isCoupons !=1 && couponType != 3 " class="c-fs20 c-text-ellipsis1">{{item.redeemType == 26 ? '适用于知识商品' : item.redeemType == 25 ? '适用于商城商品' : item.redeemType == 114 ? '适用于预约师资功能' : item.redeemType == 27 ? ("适用于" + (item.prodTypes ? item.prodTypes.join('、') : '')) : '指定商品可用'}}</div>
            <div v-if="isCoupons ==1" class="theme-fc c-fs24">{{item.usePoints}}{{customPointName}}</div>
          </div>
        </div>
        <div :class="couponType == 1 || (isCoupons == 1 && item.type == 1)? 'exchange-left' : couponType == 3 && item.type == 2 ? 'voucherFree_left' :  couponType == 3 && item.type == 6 ? 'voucherCharge_left' : 'coupon-left'" class="c-fc-white c-fs20 c-hh160 c-ww160 c-flex-column c-flex-center c-textAlign-c c-p">
          <div class="points"></div>
          <div v-if="(couponType == 2 && (item.type == 2 || item.type == 3)) || couponType == 3">
            <div class="c-fw-b">{{'￥' | iosPriceFilter}}<span class="c-fs32 c-lh36">{{Number(item.price)}}</span></div>
            <div class="opacity8">{{couponType == 3 ? '代金券面额' : Number(item.amount) > 0 ? '满'+Number(item.amount)+'可用' : '无门槛'}}</div>
          </div>
          <div class="c-fs32 c-fc-white" v-if="couponType == 2 && item.type == 4">
            抵价券
          </div>
          <div v-if="couponType == 2 && item.type == 5">
            <div class="c-fw-b c-fs32 c-lh36">{{Number(item.price)}}<span class="c-fs20">折</span></div>
            <div class="opacity8">{{Number(item.amount) > 0 ? '满'+Number(item.amount)+'可用' : '无门槛'}}</div>
          </div>
          <div class="c-fs32 c-fc-white" v-if="couponType == 1 || isCoupons == 1 && item.type == 1">
            兑换券
          </div>
          <div @click="goMyValueVoucher(item.redeemCodeId, item.fromModule)" v-if="item.hasReceive >= item.limit && item.limit != -1 && item.prodType != ckfrom.shareholderPayVoucher" class="c-fs18 c-fw-b c-ww100 c-hh36 c-lh36 c-textAlign-c c-br18 c-mt14" :class="couponType == 1 ? 'c-bg-white c-fc-D5A357' : 'c-bd1-white c-fc-white'">{{couponType == 1 ? '立即查看' : '去使用'}}</div>
          <div @click="goMyValueVoucher(item.redeemCodeId, item.fromModule)" v-else-if="item.prodType == ckfrom.shareholderPayVoucher && ((item.hasReceive > 0 && (item.limit - item.hasReceive) == 0) || ((item.hasReceive == 0 && item.leftNum == 0) || item.status > 2))" class="c-fs18 c-fw-b c-ww100 c-hh36 c-lh36 c-textAlign-c c-br18 c-mt14" :class="item.hasReceive > 0 && (item.limit - item.hasReceive) == 0 ? 'c-fc-white c-bd1-white' : 'c-fc-white c-translucent-white50'">{{item.hasReceive > 0 && (item.limit - item.hasReceive) == 0 ? '去使用' : '已领完'}}</div>
          <div v-else class="c-fs18 c-fw-b c-ww100 c-hh36 c-lh36 c-bg-white c-textAlign-c c-br18 c-mt14" :class="couponType == 2 ? 'c-fc-FF4A35' : couponType == 1 ? 'c-fc-D5A357' : 'theme-fc'" @click.stop="getCoupon(index, item.redeemCodeId, item.redeemId, item.redeemType, item.courseType, item.goodsId, item.type, item.fromModule)">{{isCoupons !=1 ? (item.type ==6 ? '立即购买' : '立即领取') : '立即兑换'}}</div>
        </div>
      </div>
      <loading-status-tem :dataStatus="dataStatus" :noDataText="couponType == 1 ? '暂无任何兑换券哦' : '暂无任何优惠券哦'"></loading-status-tem>
    </div>
  </div> -->
</template>

<script>
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import couponItemCom from "@/components/templates/couponItemCom.vue";
import {
  utilJs
} from "@/utils/common.js";
let pageIndex = 0;
let LIMIT = 10;
export default {
  name: "ValueVoucher",
  components: {
    loadingStatusTem,
    MySmallTabbar,
    couponItemCom
  },
  props: [],
  data() {
    return {
      customPointName: localStorage.getItem("customPointName"),
      theme: localStorage.getItem("colorName") || "mb5_default",
      dataStatus: 'HAS_MORE_DATA',
      ckfrom: global.ckFrom,
      valueVoucherList: [],
      isMall: '',
      searchText: '',
      couponType: 2, //2 优惠券 1 兑换券, 3 代金券
      isCoupons: '', //1积分商城 积分兑好券
      isApp: false,
      tabList: [{
        title: '优惠券',
        index: 2
      }, {
        title: '兑换券',
        index: 1
      }],
      productType: '',
      modulesKey: "", //首页中各模块索引值
      mId: "", //微页面id
    };
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() { },
  methods: {
    // 切换兑换码页面
    switchExchange(couponType) {
      this.valueVoucherList = [];
      pageIndex = 1;
      this.couponType = couponType;
      this.dataStatus = 'HAS_MORE_DATA';
      if (couponType == 3) {
        this.getVoucher(1)
      } else {
        this.getList();
      }
    },
    //跳转到个人中心我的优惠券
    goMyValueVoucher(codeId, fromModule) {
      if (this.couponType == 3) {
        this.$routerGo(this, "push", {
          path: '/homePage/shareholder/shCouponDetail',
          query: {id: codeId, rcdId: '', fromModule: fromModule, source: 21}
        })
      } else {
        this.$routerGo(this, "push", {
          path: '/member/myValueVoucher/myValueVoucher',
          query: {couponType: this.couponType}
        })
      }
    },
    goExchangePoint(goodsId) {
      this.$routerGo(this, "push", {
        path: '/member/myIntegral/integralProduct',
        query: {
          goodsId: goodsId,
        }
      })
    },
    //领取优惠券
    getCoupon(cIndex, codeId, rId, rType, courseType, goodsId, cType, fromModule) {
      if (this.isCoupons == 1) {
        this.$routerGo(this, "push", {
          path: '/member/myIntegral/integralProduct',
          query: {
            goodsId: goodsId,
          }
        })
      } else if (this.couponType == 3) {
        this.$routerGo(this, "push", {
          path: '/homePage/shareholder/shCouponDetail',
          query: {id: codeId, rcdId: '', fromModule: fromModule, source: 21}
        })
      } else {
        if (localStorage.getItem("enableBindPhoneInRedeemCode") == 1 && !localStorage.getItem("uMobile")) {
          utilJs.goBindMobile();
        } else {
          let $this = this;
          //sourc==2：从首页领取
          utilJs.postMethod(global.apiurl + "redeemCodes/collectRedeemCodeId/" + codeId, {source: 2}, function (res) {
            if (res.status != 8 && res.status != 15) {
              $this.$showCjToast({
                text: res.detail,
                type: 'warn'
              });
              return;
            }
            $this.valueVoucherList[cIndex].hasReceive++;
            $this.$cjConfirm({
              message: '恭喜您，领取成功！',
              confirmButtonText:'去使用',
              onConfirm:() => {
                if ((res.prodInfo && JSON.stringify(res.prodInfo) === '[]') || rType == 27) {
                  let toPath = rType == 25 ? '/mall/classification/classificationAll' : cType == 4 ? '/homePage/booking/bookingList' : "/";
                  $this.$routerGo($this, "push", {
                    path: toPath
                  });
                } else {
                  $this.$routerGo($this, "push", {
                    path: "/member/myExchange/toExchange",
                    query: { eExchangeCode: res.eRcdId, cType: cType }
                  });
                }
              }
            })
          }
          );
        }
      }
    },
    //获取优惠券列表
    getList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.$loading.show();
      this.dataStatus = 'LOADING';
      let url = this.isCoupons == 1 ? `pointMall/couponList?page=${pageIndex}&limit=${LIMIT}` : `redeemCodes/couponList?page=${pageIndex}&name=${this.searchText}&isMall=${this.isMall}&type=${this.couponType}&productType=${this.productType}`;
      utilJs.getMethod(`${global.apiurl}${url}`, res => {
        if (pageIndex == 1) {
          this.valueVoucherList = res.data;
        } else {
          this.valueVoucherList = [...this.valueVoucherList, ...res.data];
        }
        //隐藏课程的兑换券不需要展示
        this.valueVoucherList = this.valueVoucherList.filter(function (cv) {
          return cv.otherStatus != 1;
        })
        if (res.data && (res.data.length < LIMIT)) {
          this.dataStatus = pageIndex == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
        } else {
          this.dataStatus = 'HAS_MORE_DATA';
          pageIndex++;
        }
        this.$loading.hide();
      }, failRes => {
        this.$loading.hide();
        this.dataStatus = 'DATA_ERROR';
      }
      );
    },
    getVoucher(type) {
      utilJs.getMethod(`${global.apiurl}OaIndex/getVoucherList?mid=${this.mId}&modules_key=${this.modulesKey}&themeName=${localStorage.getItem("themeName")}`, res => {
        if (this.couponType == 3) {
          this.valueVoucherList = res;
          this.dataStatus = 'NO_MORE_DATA';
        }
        // 刚进页面 && 列表有数据 && (自定义模板 || 微页面) && 开启股东模块
        if (type == 0 && res.length > 0 && (localStorage.getItem("themeName") == 'mb7' || localStorage.getItem("themeName") == 'mb8') && JSON.parse(localStorage.getItem("companyAuth")).shareholderLevels) {
          this.tabList.splice(1, 0, {title: '代金券', index: 3})
        }
      }, failRes => {
        this.dataStatus = 'DATA_ERROR';
      });
    },
    //分享
    wechatShare: function () {
      let title = this.isCoupons == 1 ? this.customPointName + '兑换' : window.localStorage.getItem("shareTitle");
      let shareImg = window.localStorage.getItem("shareLogo");
      let isCoupons = this.isCoupons == 1 ? '1&isMall=1' : '';
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/valueVoucher/list?isCoupons=${isCoupons}&productType=${this.productType}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = window.localStorage.getItem("shareDesc");
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { });
    },
    //手机端分享
    appShare: function () {
      let title = this.isCoupons == 1 ? this.customPointName + '兑换' : window.localStorage.getItem("shareTitle");
      let isCoupons = this.isCoupons == 1 ? '1&isMall=1' : '';
      var shareUrl = `${window.location.href.split("#")[0]}#/homePage/valueVoucher/list?isCoupons=${isCoupons}&productType=${this.productType}&refereeId=${localStorage.getItem("userId")}`;
      utilJs.appShareTrue(title, "", shareUrl, "");
    },
    //下滑加载更多
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.valueVoucherList.length > 0 && this.couponType != 3) {
          this.getList();
        }
      });
    },
  },
  activated() {
    //优惠券列表
    this.isCoupons = this.$route.query.isCoupons || '';
    this.modulesKey = this.$route.query.modulesKey || '';
    this.mId = this.$route.query.mId || '';
    if (this.isCoupons == 1) {
      setDocumentTitle(this.customPointName+"兑换");// eslint-disable-line
    } else {
      setDocumentTitle("优惠券");// eslint-disable-line
    }
    pageIndex = 1;
    this.couponType = this.$route.query.couponType || 2;
    this.productType = this.$route.query.productType || '';
    this.isMall = this.$route.query.isMall || ''; //来自商城优惠券
    this.isApp = utilJs.isAndroidApp() || utilJs.isIOSApp();
    this.dataStatus = 'HAS_MORE_DATA';
    this.valueVoucherList = [];
    this.tabList = [{title: '优惠券', index: 2 }, {title: '兑换券', index: 1}];
    this.searchText = '';
    this.getList();
    this.getVoucher(0);
    this.wechatShare();
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  deactivated() {
    this.dataStatus = 'NO_MORE_DATA';
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.coupon-left {
  background: -webkit-linear-gradient(314deg, #FF8165, #FF4A35);
}
.exchange-left {
  background: -webkit-linear-gradient(314deg, #F5D199, #D5A357);
}
.voucherCharge_left {
  background: url("../../../../public/i/wap/coupon/voucherCharge_left.png") no-repeat 100%;
  background-size: 100% 100%;
}
.voucherFree_left {
  background: url("../../../../public/i/wap/coupon/voucherFree_left.png") no-repeat 100%;
  background-size: 100% 100%;
}
.c-pv17 {
  padding-top: 0.425rem;
  padding-bottom: 0.425rem;
}
.c-mt30 {
  margin-top: 0.75rem;
}
.points::before{
  content: "";
  background-color: #F6F7F8;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  top: -6px;
  left: -6px;
  position: absolute;
}
.points::after{
  content: "";
  background-color: #F6F7F8;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  bottom: -6px;
  left: -6px;
  position: absolute;
}
.c-fc-FF4A35 {
  color: #FF4A35;
}
.c-fc-D5A357 {
  color: #D5A357;
}
.opacity8 {
  opacity: .8;
}
</style>
